//
//  KLMyShopViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/29.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLMyShopViewController.h"
#import "KLMineShopTableViewCell.h"
#import "KLShopPresentViewController.h"
#import "KLAddGoodViewController.h"
#import "UITableView+STNoresult.h"
#import "KLGoodDetailModel.h"
#import "KLMenuControl.h"
#import "KLDiscountAddGoodViewController.h"
#import "KLTobeEspeciallyViewController.h"
#import "KLRenewViewController.h"
#import "KLShopOrderViewController.h"
#import "KLShopZhekouViewController.h"

#pragma mark --addGoodVC
#import "KLNewSendCarViewController.h"
#import "KLNewSendHotelViewController.h"
#import "KLNewSendBlanketViewController.h"
#import "KLNewYunJiaSuSendViewController.h"
@interface KLMyShopViewController ()
@property(nonatomic, strong) NSMutableArray <KLGoodDetailModel*>                    *dataSouce;
@property(nonatomic, strong) STButton                     *commitButton;
@property(nonatomic, strong) NSNumber * isEspeciall ;//0 未申请，1审核中，2通过，3拒绝
@property(nonatomic, strong) KLMenuControl                     *todayControl;
@property(nonatomic, strong) KLMenuControl                     *allControl;
@property(nonatomic, strong) KLMenuControl                     *zhekouControl;
@property(nonatomic, strong) KLMenuControl                     *orderControl;
@property(nonatomic, strong) STButton                     *shopButton;
@end

@implementation KLMyShopViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的商铺";
    self.view.backgroundColor = self.tableView.backgroundColor;
    self.tableView.st_noreslutView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 250, UIScreenWidth, 300) title:@"暂无添加商品" buttonTitle:@"添加商品" buttonHandle:^(NSString *titleString) {
        [self onSelectedCommitButton];
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendMyGoodsListRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    [self configHeaderView];
    [self configFooterView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, [KLUtils navgationBarBootom], UIScreenWidth, self.commitButton.top -[KLUtils navgationBarBootom] );
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configFooterView{
    __weak typeof(self) weakSelf =  self;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(0, [KLUtils tabBarTop], UIScreenWidth, 49)
                                                        title:@"+添加商品"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:0
                                              backgroundColor:KL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitButton];
    }];
    
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.commitButton = confimButton;
    self.commitButton.hidden = YES;
    [self.view addSubview:confimButton];
    
}
- (void)configHeaderView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 40)];
    header.backgroundColor = [UIColor whiteColor];
    
//    self.todayControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 2, 70) value:@"0：00" name:@"今日收入" showLine:YES];
//    [header addSubview:self.todayControl];
    
//    self.allControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(self.todayControl.right, 0, UIScreenWidth / 2, 70) value:@"0：00" name:@"总收入" showLine:NO];
//    [header addSubview:self.allControl];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 0.5)];
    line.backgroundColor = KL_lineColor;
    [header addSubview:line];
    
    self.zhekouControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(0, line.bottom, UIScreenWidth / 3, 70) value:@"0：00" name:@"折扣券订单" showLine:YES];
    [self.zhekouControl addTarget:self action:@selector(onSelctedZhekouOrderConrtrol) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:self.zhekouControl];
    
    self.orderControl = [[KLMenuControl alloc] initWithFrame:CGRectMake(self.zhekouControl.right, line.bottom, UIScreenWidth / 3, 70) value:@"0：00" name:@"价格订单" showLine:YES];
    [self.orderControl addTarget:self action:@selector(onSelctedShopOrderConrtrol) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:self.orderControl];
    
    
    __weak typeof(self) weakSelf =  self;
    self.shopButton = [[STButton alloc] initWithFrame:CGRectMake(self.orderControl.right, line.bottom, UIScreenWidth / 3, 70)
                                                title:@"店铺续费"
                                           titleColor:KL_secendTextColor
                                            titleFont:15
                                         cornerRadius:0
                                      backgroundColor:nil
                                      backgroundImage:nil
                                                image:nil];
    self.shopButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.shopButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedRenewButton];
    }];
    [header addSubview:self.shopButton];
    
    header.height= self.shopButton.bottom;
    self.tableView.tableHeaderView = header;
    
}

- (void)reloadData{
    self.commitButton.hidden = !self.dataSouce.count;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [KLMineShopTableViewCell CellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [KLUtils headerViewWithTitle:@"商品信息"];
    return view;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    KLMineShopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[KLMineShopTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataSouce[indexPath.row];
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self sendDelGoodRequestWithIndexPath:indexPath];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    KLGoodDetailModel *  shopmodel = self.dataSouce[indexPath.row];
    if (shopmodel.classification.integerValue == 2) {
        [KLUtils fecthGoodDetailWithID:shopmodel.goodID.description hanlde:^(KLGoodDetailModel *model, STError *error) {
            KLNewSendCarViewController * vc = [KLNewSendCarViewController new];
            vc.goodModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];

    }
    if (shopmodel.classification.integerValue == 8) {
        [KLUtils fecthGoodDetailWithID:shopmodel.goodID.description hanlde:^(KLGoodDetailModel *model, STError *error) {
            KLNewSendHotelViewController * vc = [KLNewSendHotelViewController new];
            vc.goodModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
    }
    
    if (shopmodel.classification.integerValue == 4) {
        [KLUtils fecthGoodDetailWithID:shopmodel.goodID.description hanlde:^(KLGoodDetailModel *model, STError *error) {
            KLNewSendBlanketViewController * vc = [KLNewSendBlanketViewController new];
            vc.goodModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
    }
    if (shopmodel.classification.integerValue == 3) {
        [KLUtils fecthGoodDetailWithID:shopmodel.goodID.description hanlde:^(KLGoodDetailModel *model, STError *error) {
            KLNewYunJiaSuSendViewController * vc = [KLNewYunJiaSuSendViewController new];
            vc.goodModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
    }
    if (shopmodel.classification.integerValue == 1) {
        //各地特产和匀加速一样
        [KLUtils fecthGoodDetailWithID:shopmodel.goodID.description hanlde:^(KLGoodDetailModel *model, STError *error) {
            KLNewYunJiaSuSendViewController * vc = [KLNewYunJiaSuSendViewController new];
            vc.goodModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
    }
    
    
//    KLGoodDetailViewController * vc = [KLGoodDetailViewController new];
//    vc.goodID = self.dataSouce[indexPath.row].goodID.description;
//    [self.navigationController pushViewController:vc animated:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSlectedRenewButton{
    KLRenewViewController * vc = [KLRenewViewController new];
    vc.shops_id = self.shops_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)st_rightBarAction:(id)sender{
    if (self.isEspeciall.integerValue == 1) {
        [SVProgressHUD showInfoWithStatus:@"您申请的地方特产正在审核中，请稍后"];
        return;
    }
    if (self.isEspeciall.integerValue == 3) {
        [SVProgressHUD showInfoWithStatus:@"您申请的地方特产已被拒绝，请重新申请"];
    }
    KLTobeEspeciallyViewController * vc =  [KLTobeEspeciallyViewController new];
    vc.shopId = self.shops_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)onSelectedCommitButton{
    [self sendShopTypesRequestWithHandle:^(NSArray *array) {
        if (array.count) {
            
            KLShopPresentViewController * vc = [[KLShopPresentViewController alloc] initWithHandle:^(KLShopTypeModel *model) {
                
                if ([model.classify_id isEqualToString:@"饭店订桌"]) {
                    [SVProgressHUD showInfoWithStatus:@"该功能正在完善"];
                    return ;
                }
                
                if ([model.classify_id isEqualToString:@"民车出租"]) {
                    KLNewSendCarViewController * vc = [KLNewSendCarViewController new];
                    vc.model = model;
                     [self.navigationController pushViewController:vc animated:YES];
                    return ;
                }
                if ([model.classify_id isEqualToString:@"宾馆住宿"]) {
                     KLNewSendHotelViewController * vc = [ KLNewSendHotelViewController new];
                    vc.model = model;
                    [self.navigationController pushViewController:vc animated:YES];
                    return ;
                }
               
                if ([model.classify_id isEqualToString:@"匀加速市场"] || [model.classify_id isEqualToString:@"各地特产"]) {
                    KLNewYunJiaSuSendViewController * vc = [KLNewYunJiaSuSendViewController new];
                    vc.model = model;
                    [self.navigationController pushViewController:vc animated:YES];
                    
                }else{
                    KLAddGoodViewController * addvc = [KLAddGoodViewController new];
                    addvc.model = model;
                    [self.navigationController pushViewController:addvc animated:YES];
                }
                
            }];
            vc.array = array;
            [self presentViewController:vc animated:NO completion:nil];
            
        }
    }];
    
}
- (void)onSelctedShopOrderConrtrol{
    [self.navigationController pushViewController:[KLShopOrderViewController new] animated:YES];
}
- (void)onSelctedZhekouOrderConrtrol{
    KLShopZhekouViewController * vc = [KLShopZhekouViewController new];
    vc.shop_id = self.shops_id;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark --NetWork Method
- (void)sendMyGoodsListRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/shop/myshops",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"goods_list"]) {
                                                     NSArray * array = dataDic[@"goods_list"];
                                                     self.dataSouce = [NSMutableArray new];
                                                     for (NSDictionary * goodDic in array) {
                                                         KLGoodDetailModel * good = [KLGoodDetailModel mj_objectWithKeyValues:goodDic];
                                                         [self.dataSouce addObject:good];
                                                     }
                                                 }
                                                 //判断是否特产
                                                 NSNumber * isEspeciall = dataDic[@"is_specialty"];
                                                 self.isEspeciall = isEspeciall;
                                                 if (isEspeciall.integerValue != 2) {
                                                     [self st_setRightItemWithTitle:@"申请地方特产" titleColor:FlatWhite];
                                                 }else{
                                                     [self st_setRightItemWithView:nil];
                                                 }
                                                 
                                                 if ([dataDic.allKeys containsObject:@"order_count"]) {
                                                     NSDictionary * order_countDic = dataDic[@"order_count"];
                                                     self.todayControl.valueLable.text = [order_countDic[@"today_count"] description];
                                                     self.allControl.valueLable.text = [order_countDic[@"total"] description];
                                                     self.zhekouControl.valueLable.text = [order_countDic[@"yun_count"] description];
                                                     self.orderControl.valueLable.text = [order_countDic[@"all_order_count"] description];
                                                 }
                                                 [self reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self reloadData];
                                                 
                                             }];
}
- (void)sendShopTypesRequestWithHandle:(void(^)(NSArray * array))handle{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.shops_id.length) {
        [dic setObject:self.shops_id forKey:@"shop_id"];
    }
    [dic setObject:@"1" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/shop/goodstype",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 NSMutableArray * array = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in dataArray) {
                                                     KLShopTypeModel * model = [KLShopTypeModel mj_objectWithKeyValues:modelDic];
                                                     [array addObject:model];
                                                 }
                                                 KLShopTypeModel * addModel  = [KLShopTypeModel new];
                                                 addModel.classify_id = @"饭店订桌";
                                                 [array addObject:addModel];
                                                 if (handle) {
                                                     handle(array);
                                                 }
                                                 
                                                 
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 if (handle) {
                                                     handle(nil);
                                                 }
                                                 
                                             }];
}

- (void)sendDelGoodRequestWithIndexPath:(NSIndexPath*)indexPath{
    [SVProgressHUD showWithStatus:@"请稍后"];
    KLGoodDetailModel * model = self.dataSouce[indexPath.row];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (model.goodID.description.length) {
        [dic setObject:model.goodID forKey:@"goods_id"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/shop/delete",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"删除成功"];
//                                                 [self.dataSouce removeObjectAtIndex:indexPath.row];
//                                                 [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
@end

